package com.cdc.retrofit;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cdc.urls.Constants;
import com.cdc.urls.Person;
import com.cdc.urls.Tools;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cdc.mvp.presenter.RequestPresenterImpl;
import cdc.mvp.view.RequestView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.content.pm.PackageManager.PERMISSION_DENIED;

public class RequestActivity extends AppCompatActivity implements RequestView{

    private TextView tvResult;

    private Retrofit retrofit;

    private RequestPresenterImpl requestPresenter;

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOAD=1;
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOADS=2;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);

        tvResult=findViewById(R.id.tvResult);

        tvResult.setMovementMethod(new ScrollingMovementMethod());

        requestPresenter=new RequestPresenterImpl();
        requestPresenter.attachView(this);
    }

    public void requestApi(View view) {
        retrofit=new Retrofit.Builder().baseUrl(Constants.IP).build();
        Api api=retrofit.create(Api.class);
        Call<ResponseBody> call=api.personBody();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                String  result= null;
                try {
                    result = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                tvResult.setText(result);

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                tvResult.setText(call.request().url().toString());
            }
        });
    }


    public void requestApiParamer(View view) {
        retrofit=new Retrofit.Builder().baseUrl(Constants.IP)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        PersonId personId=retrofit.create(PersonId.class);
        Call<Person> call=personId.personId(3);
        call.enqueue(new Callback<Person>() {
            @Override
            public void onResponse(Call<Person> call, Response<Person> response) {
                Person result = response.body();
                tvResult.setText(result.getName());
            }

            @Override
            public void onFailure(Call<Person> call, Throwable t) {
                String url=call.request().url().toString();
               Gson gson=new Gson();
                tvResult.setText(url+","+t.getMessage()+","+gson.toJson(Tools.initDefaultPerson()));
            }
        });
    }

    public void requestPathUser(View view){
        requestPresenter.restUser(3);
    }
    /**
     *
     * restful api  person
     * 使用默认的Gson解析不能解析Person这个复杂的类，此类中依赖其它类和枚举
     * addConverterFactory(FastJsonConverterFactory.create())
     *
     * **/
    public void requestPathPerson(View view){
        requestPresenter.restPerson(3);
    }

    /**
     * 返回原始的ResponseBody
     * @param view
     */
    public void requestBodyPerson(View view){
        requestPresenter.personBody();
    }



    public void personBothQuaryMap(View view){
        requestPresenter.personBothQueryMap(3,"纪晓岚");
    }

    public void personBothQuary(View view){
        requestPresenter.personBothQuary(4,"朱圭");
    }

    public void personBothForm(View view){
        requestPresenter.personBothForm(5,"王杰");
    }

    public void upPerson(View view){
        requestPresenter.upPerson(Tools.initDefaultPerson());
    }

    public void uploadPerson(View view) {
        permission(1);
    }

    public void uploadsPerson(View view) {
        permission(2);
    }

    private void permission(int tag){
        int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
            } else {
                // No explanation needed, we can request the permission.
                if(tag==1){
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOAD);
                }else if(tag==2){
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOADS);
                }

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOAD: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    File file=new File(Environment.getExternalStorageDirectory(),"1522397936091.mp4");
                    requestPresenter.uploadPerson(file,34,"种种");

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            }
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE_UPLOADS: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    File file1=new File(Environment.getExternalStorageDirectory(),"1522397936091.mp4");
                    File file2=new File(Environment.getExternalStorageDirectory(),"ic_update_black_48dp.png");
                    requestPresenter.uploadsPerson("id",34,"name","种种",file1,file2);

                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                break;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    @Override
    public void success(String result) {
        tvResult.setText(result);
    }

    @Override
    public void error(String result) {
        tvResult.setText(result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        requestPresenter.detachView();
    }

    @Override
    public void showToast(String message) {
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }


}
